package com.cah.project.util;

import cn.hutool.core.util.ObjectUtil;

import java.util.NoSuchElementException;

public final class OptionalExt<T> {

    private static final OptionalExt<?> EMPTY = new OptionalExt<>();

    private final T value;

    private OptionalExt() {
        this.value = null;
    }

    public static<T> OptionalExt<T> empty() {
        @SuppressWarnings("unchecked")
        OptionalExt<T> t = (OptionalExt<T>) EMPTY;
        return t;
    }

    private OptionalExt(T value) {
        if(ObjectUtil.isNull(value)) {
            throw new NullPointerException("对象为空");
        }
        this.value = value;
    }

    private OptionalExt(T value, String message) {
        if(ObjectUtil.isNull(value)) {
            throw new NullPointerException(message);
        }
        this.value = value;
    }

    public static <T> OptionalExt<T> of(T value) {
        return new OptionalExt<>(value);
    }

    public static <T> OptionalExt<T> of(T value, String message) {
        return new OptionalExt<>(value, message);
    }

    public static <T> OptionalExt<T> ofNullable(T value) {
        return ObjectUtil.isNull(value) ? empty() : of(value);
    }

    public T get() {
        if (ObjectUtil.isNull(value)) {
            throw new NoSuchElementException("No value present");
        }
        return value;
    }

    public T getNullMessage(String message) {
        if (ObjectUtil.isNull(value)) {
            throw new NullPointerException(message);
        }
        return value;
    }


}
